const puppeteer = require('puppeteer')

const url = `https://movie.douban.com/tag/#/?sort=U&range=6,10&tags=`

const sleep = time => new Promise(resolve =>{
	setTimeout(resolve,time)
})

;(async () => {  //定义匿名函数
	console.log('Start visit the target page')
	const browser = await puppeteer.launch({ //启动浏览器
		args: ['--no-sandbox'],
		dumpio : false
	})

	const page = await browser.newPage()
	await page.goto(url, {   //爬虫的网址
		waitUntil : 'networkidle2' //当网络空闲加载完毕
	})

	await sleep(3000) //等待3s,使页面彻底加载完毕

	await page.waitForSelector('.more')  //页面点击更多，加载数据

	for(let i = 0; i < 1; i++){  //等待3s之后，按钮出现  然后循环下
		await sleep(3000)		//只点击按钮一次
		await page.click('.more')
	}
	//这个是在浏览器中执行的
	//判断下浏览器中是不是有jquery
	//如果有，可以直接使用
	const result = await page.evaluate( () => { 
		var $ = window.$;
		var items = $('.list-wp a')
		var links = []

		if(items.length >= 1) {
			items.each((index,item) => {
				let it = $(item)
				let doubanId = it.find('div').data('id')
				let title = it.find('.title').text()
				let rate = Number(it.find('.rate').text())
				let poster = it.find('img').attr('src').replace('s_ratio','l_ratio')
					//替换缩略图
				links.push({
					doubanId,
					title,
					rate,
					poster
				})
			})
		}
		return links;
	})

	browser.close(); //关闭浏览器

	//console.log(result)
	process.send({result});
	process.exit(0);

})()